
$(function () {

    //扩展隐藏、现在
    $("#dms-api").on("click",".expand-config-direction",function () {
       var  direction = $(this).find(".expand-direction");
       direction.toggleClass("icon-youshuangjiantou").toggleClass("icon-shuangjiantouxia");

       var item = $(this).parents(".expand-config").find(".expand-config-item");
       if(direction.hasClass("icon-youshuangjiantou")){
           item.hide();
       }else {
           item.show();
       }
    });
    //字段编辑
    $("#dms-api").on("click",".field-edit",function () {
        initSqlStatementApiField(this);
    });

    //请求认证
    $("#dms-api").on("click","input[name='auth']",function () {
        var _this = $(this);
        var checkboxVal = _this.val();
        var $table = $(this).parents(".api-group").find(".api-requestHeader .treetable-body-box .treetable-table");
        if(checkboxVal == "true"){
            $table.bootstrapTreeTable("appendData",[{"id":new Date().getTime(),"parentId":0,field : "Authorization","validator" : {required:true}}]);
        }else {
            var data = $table.bootstrapTreeTable("getData");
            var ids =  data.filter(function (value) {  return value.field == "Authorization";}).map(function (value) { return value.id;});
            $table.bootstrapTreeTable("removeData",ids);
        }
    });

    //请求头添加
    $("#dms-api").on("click",".requestHeaderAdd",function () {
        var _this = $(this);
        var $table = _this.parents(".bootstrap-tree-table").find(".treetable-body-box .api-tree-table");
        $table.bootstrapTreeTable("appendData",[{"id":new Date().getTime(),"parentId":0}]);
    });

    //字段删除
    $("#dms-api").on("click",".field-remove",function () {
        var _this = $(this);
        var $table = _this.parents("table");
        var id = _this.parents("tr").attr("dataid");
        $table.bootstrapTreeTable("removeData",id);
    });

});

function renderMappedStatementApi(array) {
    var buildingArray =  Array.isArray(array) ? array.filter(function (item) {  return array.length == 1  || !item.hasOwnProperty("parentId") || !item.parentId; }) : [];
    var html =  renderMappedStatementItemApi(array,buildingArray,{index : -1},false);
    $("#dms-api .api-box").html(html.join(""));

    $("#dms-api .icon-icon-question").popover();
    $("#dms-api").data("api",array);
    renderMappedStatementApiTreeTableData(array);
    renderMappedStatementApiHeaderTreeTableData(array);
}


function renderMappedStatementItemApi(array,buildingArray,opts,collapse) {
    opts.parentIndex = opts.parentIndex || opts.parentIndex === 0 ? opts.parentIndex : opts.index;
    var html = [];
    for(var i  = 0 ; i < buildingArray.length ; i++){
        opts.index = ++opts.index;
        var dms = buildingArray[i];
        html.push("<div class='api-group "+(collapse ? "collapse collapse-api"+opts.parentIndex : "")+"'>");

        html.push("<div class='api-mappedStatement'>");
        html.push("<form class=''>");

        html.push("<div class='form-group row'>");
        html.push("<label  class='col-form-label col-sm-3' >地址:</label>");
        if(dms.commandType == 'MERGE'){
            html.push("<div class='input-group col-sm-8'>");
            html.push("<div class='input-group-prepend'><div class='input-group-text'>/"+dms.namespace+"/</div></div>");
            html.push("<input type='text' class='form-control' name='shortId'  value='"+(dms.shortId.replace(/\./g,"/"))+"' /></span>");
            html.push("</div>");
        }else {
            html.push("<div class='col-sm-8'>");
            html.push("<input type='text' class='form-control' name='viewId' readonly   value='/"+(dms.id.replace(/\./g,"/"))+"'>");
            html.push("</div>");
        }
        html.push("</div>");

        html.push("<div class='form-group row'>");
        html.push("<label class='col-form-label col-sm-3' >名称:</label>");
        html.push("<div class='col-sm-8'>");
        html.push("<input class='form-control' name='name' value='"+(dms.name ? dms.name :"")+"' />");
        html.push("</div>");
        html.push("</div>");

       var dataSources = $("#dataSourceCodes").data("dataSources");
        html.push("<div class='form-group row'>");
        html.push("<label class='col-form-label col-sm-3' >数据源:</label>");
        html.push("<div class='col-sm-8'>");
        html.push("<select class='form-control' name='targetDataSourceKey' >");
        if(dataSources){
            for(var j = 0 ; j < dataSources.length ; j++){
                var checked = dms.targetDataSourceKey == dataSources[j].code;
                html.push("<option "+(checked ? "selected" :"")+" value='"+dataSources[j].code+"'>"+dataSources[j].code+"</option>");
            }
        }
        html.push("</select>");
        html.push("</div>");
        html.push("</div>");

        var returnType = dms.returnType;
        html.push("<div class='form-group row'>");
        html.push("<label class='col-form-label col-sm-3' >返回类型:</label>");
        html.push("<div class='col-sm-8'>");
        html.push("<select class='form-control' name='returnType'>");
        html.push("<option value=''>请选择</option>");
        html.push("<option value='COLLECT' "+(returnType =="COLLECT" ? "selected" : "")+">COLLECT</option>");
        html.push("<option value='PAGE' "+(returnType =="PAGE" ? "selected" : "")+">PAGE</option>");
        html.push("<option value='MAP' "+(returnType =="MAP" ? "selected" : "")+">MAP</option>");
        html.push("<option value='STRING' "+(returnType =="STRING" ? "selected" : "")+">STRING</option>");
        html.push("<option value='BOOLEAN' "+(returnType =="BOOLEAN" ? "selected" : "")+">BOOLEAN</option>");
        html.push("<option value='BYTE' "+(returnType =="BYTE" ? "selected" : "")+">BYTE</option>");
        html.push("<option value='SHORT' "+(returnType =="SHORT" ? "selected" : "")+">SHORT</option>");
        html.push("<option value='INTEGER' "+(returnType =="INTEGER" ? "selected" : "")+">INTEGER</option>");
        html.push("<option value='LONG' "+(returnType =="LONG" ? "selected" : "")+">LONG</option>");
        html.push("<option value='DATE' "+(returnType =="DATE" ? "selected" : "")+">DATE</option>");
        html.push("<option value='TIME' "+(returnType =="TIME" ? "selected" : "")+">TIME</option>");
        html.push("<option value='TIMESTAMP' "+(returnType =="TIMESTAMP" ? "selected" : "")+">TIMESTAMP</option>");
        html.push("<option value='FLOAT' "+(returnType =="FLOAT" ? "selected" : "")+">FLOAT</option>");
        html.push("<option value='DOUBLE' "+(returnType =="DOUBLE" ? "selected" : "")+">DOUBLE</option>");
        html.push("</select>");
        html.push("</div>");
        html.push("</div>");

        html.push("<div class='expand-config'>");

        html.push("<div class='form-group row'>");
        html.push("<label class='col-form-label col-sm-3 expand-config-direction' ><h5>扩展配置:</h5><span class='expand-direction iconfont icon-youshuangjiantou'></span></label>");
        html.push("</div>");

        html.push("<div class='expand-config-item'>");

        html.push("<div class='form-group row '>");
        html.push("<label class='col-form-label col-sm-3' >状态:</label>");
        html.push("<div class='col-sm-8'>");
        html.push("<div class=\"form-check form-check-inline col-sm-6\">");
        html.push("<input type=\"radio\" class=\"form-check-input\" "+(dms.enable ? "checked" :"")+" name=\"enable\" id=\"enableTrue\" value=\"true\">");
        html.push("<label class=\"form-check-label\">启用</label>");
        html.push("</div>");
        html.push("<div class=\"form-check form-check-inline col-sm-6\">");
        html.push("<input type=\"radio\" class=\"form-check-input\" "+(!dms.enable ? "checked" :"")+" name=\"enable\" id=\"enableFalse\" value=\"false\">");
        html.push("<label class=\"form-check-label\">禁用</label>");
        html.push("</div>");
        html.push("</div>");
        html.push("</div>");

        html.push("<div class='form-group row'>");
        html.push("<label class='col-form-label col-sm-3' >事务:</label>");
        html.push("<div class='col-sm-8'>");
        html.push("<div class=\"form-check form-check-inline col-sm-6\">");
        html.push("<input type=\"radio\" class=\"form-check-input\" "+(dms.transaction ? "checked" :"")+" name=\"transaction\" id=\"transactionTrue\" value=\"true\">");
        html.push("<label class=\"form-check-label\">开启</label>");
        html.push("</div>");
        html.push("<div class=\"form-check form-check-inline col-sm-6\">");
        html.push("<input type=\"radio\" class=\"form-check-input\" "+(!dms.transaction ? "checked" :"")+" name=\"transaction\" id=\"transactionFalse\" value=\"false\">");
        html.push("<label class=\"form-check-label\">关闭</label>");
        html.push("</div>");
        html.push("</div>");
        html.push("</div>");

        html.push("<div class='form-group row'>");
        html.push("<label class='col-form-label col-sm-3' >入参包装:</label>");
        html.push("<div class='col-sm-8'>");
        html.push("<input class='form-control' name='parameterWrapper' value='"+(dms.parameterWrapper ? dms.parameterWrapper :"")+"' />");
        html.push("</div>");
        html.push("</div>");

        html.push("<div class='form-group row'>");
        html.push("<label class='col-form-label col-sm-3' >结果包装:</label>");
        html.push("<div class='col-sm-8'>");
        html.push("<input class='form-control' name='resultWrapper' value='"+(dms.resultWrapper ? dms.resultWrapper :"")+"' />");
        html.push("</div>");
        html.push("</div>");

        html.push("<div class='form-group row'>");
        html.push("<label class='col-form-label col-sm-3' >批处理:</label>");
        html.push("<div class='col-sm-8'>");
        html.push("<div class=\"form-check form-check-inline col-sm-6\">");
        html.push("<input type=\"radio\" class=\"form-check-input\" "+(dms.batch ? "checked" :"")+" name=\"batch\" id=\"batchTrue\" value=\"true\">");
        html.push("<label class=\"form-check-label\">是&nbsp;&nbsp;&nbsp;&nbsp;</label>");
        html.push("</div>");
        html.push("<div class=\"form-check form-check-inline col-sm-6\">");
        html.push("<input type=\"radio\" class=\"form-check-input\" "+(!dms.batch ? "checked" :"")+" name=\"batch\" id=\"batchFalse\" value=\"false\">");
        html.push("<label class=\"form-check-label\">否&nbsp;&nbsp;&nbsp;&nbsp;</label>");
        html.push("</div>");
        html.push("</div>");
        html.push("</div>");

        html.push("<div class='form-group row'>");
        html.push("<label class='col-form-label col-sm-3' >批次大小:</label>");
        html.push("<div class='col-sm-8'>");
        html.push("<input class='form-control' name='batchSize' value='"+(dms.batchSize ? dms.batchSize :"")+"' />");
        html.push("</div>");
        html.push("</div>");

        html.push("<div class='form-group row'>");
        html.push("<label class='col-form-label col-sm-3' >web接口:</label>");
        html.push("<div class='col-sm-8'>");
        html.push("<div class=\"form-check form-check-inline col-sm-6\">");
        html.push("<input type=\"radio\" class=\"form-check-input\" "+(dms.rest ? "checked" :"")+" name=\"rest\" id=\"restTrue\" value=\"true\">");
        html.push("<label class=\"form-check-label\">是&nbsp;&nbsp;&nbsp;&nbsp;</label>");
        html.push("</div>");
        html.push("<div class=\"form-check form-check-inline col-sm-6\">");
        html.push("<input type=\"radio\" class=\"form-check-input\" "+(!dms.rest ? "checked" :"")+" name=\"rest\" id=\"restFalse\" value=\"false\">");
        html.push("<label class=\"form-check-label\">否&nbsp;&nbsp;&nbsp;&nbsp;</label>");
        html.push("</div>");
        html.push("</div>");
        html.push("</div>");

        var method = dms.method;
        html.push("<div class='form-group row'>");
        html.push("<label class='col-form-label col-sm-3' >请求方式:</label>");
        html.push("<div class='col-sm-8'>");
        html.push("<select class='form-control api-method' name='method'>");
        html.push("<option value=''>请选择</option>");
        html.push("<option value='GET' "+(method =="GET" ? "selected" : "")+">GET</option>");
        html.push("<option value='POST' "+(method =="POST" ? "selected" : "")+">POST</option>");
        html.push("<option value='PUT' "+(method =="PUT" ? "selected" : "")+">PUT</option>");
        html.push("<option value='DELETE' "+(method =="DELETE" ? "selected" : "")+">DELETE</option>");
        html.push("<option value='HEAD' "+(method =="HEAD" ? "selected" : "")+">HEAD</option>");
        html.push("<option value='OPTIONS' "+(method =="OPTIONS" ? "selected" : "")+">OPTIONS</option>");
        html.push("<option value='PATCH' "+(method =="PATCH" ? "selected" : "")+">PATCH</option>");
        html.push("<option value='TRACE' "+(method =="TRACE" ? "selected" : "")+">TRACE</option>");
        html.push("</select>");
        html.push("</div>");
        html.push("</div>");

        html.push("<div class='form-group row'>");
        html.push("<label class='col-form-label col-sm-3' >请求认证:</label>");
        html.push("<div class='col-sm-8'>");
        html.push("<div class=\"form-check form-check-inline col-sm-6\">");
        html.push("<input type=\"radio\" class=\"form-check-input\" "+(dms.auth ? "checked" :"")+" name=\"auth\" id=\"authTrue\" value=\"true\">");
        html.push("<label class=\"form-check-label\">是&nbsp;&nbsp;&nbsp;&nbsp;</label>");
        html.push("</div>");
        html.push("<div class=\"form-check form-check-inline col-sm-6\">");
        html.push("<input type=\"radio\" class=\"form-check-input\" "+(!dms.auth ? "checked" :"")+" name=\"auth\" id=\"authFalse\" value=\"false\">");
        html.push("<label class=\"form-check-label\">否&nbsp;&nbsp;&nbsp;&nbsp;</label>");
        html.push("</div>");
        html.push("</div>");
        html.push("</div>");

        html.push("<div class='form-group row'>");
        html.push("<label class='col-form-label col-sm-3 session-context-question' >");
        html.push("<span class='icon iconfont icon-icon-question' data-toggle='popover' data-content='将结果集作为用户session上下文,并将该接口参数转换为token作为结果集'></span>");
        html.push("会话:</label>");
        html.push("<div class='col-sm-8'>");
        html.push("<div class=\"form-check form-check-inline col-sm-6\">");
        html.push("<input type=\"radio\" class=\"form-check-input\" "+(dms.sessionContext ? "checked" :"")+" name=\"sessionContext\" id=\"sessionContextTrue\" value=\"true\">");
        html.push("<label class=\"form-check-label\">是&nbsp;&nbsp;&nbsp;&nbsp;</label>");
        html.push("</div>");
        html.push("<div class=\"form-check form-check-inline col-sm-6\">");
        html.push("<input type=\"radio\" class=\"form-check-input\" "+(!dms.sessionContext ? "checked" :"")+" name=\"sessionContext\" id=\"sessionContextFalse\" value=\"false\">");
        html.push("<label class=\"form-check-label\">否&nbsp;&nbsp;&nbsp;&nbsp;</label>");
        html.push("</div>");
        html.push("</div>");
        html.push("</div>");

        html.push("</div>");
        html.push("</div>");

        html.push("</form>");
        html.push("</div>");


        html.push("<div class='api-requestHeader'>");
        html.push("<h5>请求头</h5>");
        html.push("<table class='api-tree-table' id='requestHeaderTable"+opts.index+"'></table>");
        html.push("</div>");

        html.push("<div class='api-inputParameter'>");
        html.push("<h5>请求数据</h5>");
        html.push("<table class='api-tree-table' id='inputParameterTable"+opts.index+"'></table>");
        html.push("</div>");


        html.push("<div class='api-outputParameter'>");
        html.push("<h5>响应数据</h5>");
        html.push("<table class='api-tree-table' id='outputParameterTable"+opts.index+"'></table>");
        html.push("</div>");

        html.push("</div>");

        var children = array.filter(function (item) {  return item.parentId == dms.id; });

        if(children && children.length > 0){
            opts.parentIndex = opts.index;
           html.push("<a class='btn btn-link btn-link-collapse' data-toggle='collapse' href='.collapse-api"+(opts.parentIndex)+"' aria-expanded='false' aria-controls='collapseApi'>明细</a>");

           html.push.apply(html,renderMappedStatementItemApi(array,children,opts,true));
        }
    }
    return html;

}

function renderMappedStatementApiTreeTableData(array) {
    var apiBox = $("#dms-api").find(".api-group");
    var columns = [
        { field: "field", title : "参数", width:"30%"},
        { field: "name", title : "名称",align : "center",width:"20%",formatter : function (value, row, index) {
            return "<input type='text' class='form-control' name='name' value='"+(value || value === 0 ? value :"")+"'/>";
        } },
        { field: "mergeType", title : "类型",align : "center",width:"20%" ,formatter: function (value, row, index) {
            var type = row.type ;
            if(row.type){
                type = row.genericType ?  row.type+"("+row.genericType+")" : type;
            }else {
                type = "";
            }
            return type;
       }},

/*        { field: "visible", title : "显示", align : "center",width:"10%",valign : "middle",formatter : function (value, row, index) {
                var checked = value && value && !(value === "false") ? "checked" : "";
                return "<input type='checkbox' class='form-check-input' name='visible' value='true' "+checked+"/>";
        }},*/
        { field: "enable", title : "校验", align : "center",width:"10%",valign : "middle",formatter : function (value, row, index) {
                var checked = row.validator && row.validator.enable && !(row.validator.enable === "false") ? "checked" : "";
                return "<input type='checkbox' class='form-check-input' name='enable' value='true' "+checked+"/>";
        }},
        { field: "operate", title : "操作",align : "center",width:"15%",valign : "middle",formatter : function (value, row, index) {
                return "<span  class='btn btn-link field-edit icon iconfont icon-bianji' ></span>" +
                    "<span  class='btn btn-link field-remove icon iconfont icon-shanchu' ></span>";
        }},
    ];
    var tables = {
        ".api-inputParameter table" : "inputParameter",
        ".api-outputParameter table" : "outputParameter"
    };
    for(var i = 0 ; i < apiBox.length ; i++){
        if(!array[i]){ continue;}
        for(var item in tables){
            var table = $(apiBox[i]).find(item);
            table.bootstrapTreeTable({
                columns : columns,
                data :array[i][tables[item]],
                showColumns : false,
                showRefresh : false,
                width: "100%",
            });
        }
    }
}


function renderMappedStatementApiHeaderTreeTableData(array) {
    var apiBox = $("#dms-api").find(".api-group");
    var columns = [
        {field : "id",title : "id",visible:false},
        { field: "field", title : "键", align : "center", width:"30%",valign : "middle",formatter : function (value, row, index) {
                return "<input type='text' class='form-control' name='field' value='"+(value || value === 0 ? value :"")+"'/>";
        }},
        { field: "defaultValue", title : "值", align : "center",width:"25%",valign : "middle",formatter : function (value, row, index) {
                return "<input type='text' class='form-control' name='defaultValue' value='"+(value || value === 0 ? value :"")+"'/>";
         }},
        { field: "required", title : "必填", align : "center",width:"10%",valign : "middle",formatter : function (value, row, index) {
                var checked = row.validator && row.validator.required && !(row.validator.required === "false") ? "checked" : "";
                return "<input type='checkbox' class='form-check-input' name='required' value='true' "+checked+"/>";
            }},
        { field: "operate", title : "操作 <span class='iconfont icon-add btn-link requestHeaderAdd'></span>",align : "center",width:"15%",valign : "middle",formatter : function (value, row, index) {
                return  "<span  class='btn btn-link field-edit icon iconfont icon-bianji' ></span>" +
                    "<span  class='btn btn-link field-remove icon iconfont icon-shanchu' ></span>";
        }},
    ];
    for(var i = 0 ; i < apiBox.length ; i++){
        if(!array[i]){ continue;}
        var table = $(apiBox[i]).find(".api-requestHeader table");
        table.bootstrapTreeTable({
            columns : columns,
            data :array[i]["requestHeader"],
            showColumns : false,
            showRefresh : false,
            width: "100%",
        });
    }
}

//获取api和api字段数据
function getMappedStatementApiData(number) {
    var apis = $("#dms-api").find(".api-group");
    var array = [];
    var propertyKey = {
        "#inputParameterTable" : "inputParameter",
        "#requestHeaderTable" : "requestHeader",
        "#outputParameterTable" : "outputParameter"
    };
    var dmsApiArray = $("#dms-api").data("api");
    var parameters =  $("#dms-execute").find("textarea[name='inputParameter']");
    for(var i = 0 ; i < apis.length ; i++){
        if((number || number === 0) && number != i){
            continue
        }
        var apiDms =  $(apis[i]).find(".api-mappedStatement");
        var dms = apiDms.serializable();
        dms = $.extend({},dmsApiArray[i] || {},dms);
        for(var key in propertyKey){
            dms[propertyKey[key]] = [];
            var tableData =  $(apis[i]).find(key+i).bootstrapTreeTable("getData");
            var tableInputData = $(apis[i]).find(key+i).serializable();
            for(var j = 0 ; j < tableData.length ; j++){
                var row1  = tableData[j];
                var row2 = tableInputData[j];
                var row = $.extend({},row1,row2);
                row.validator =  row.validator ? row.validator : {};
                row.validator.required = !!row.required;
                row.validator.enable = !!row.enable;
                dms[propertyKey[key]].push(row);
            }
        }
        //获取mock数据
        dms.inputParameterMock = JSON.parse($(parameters[i]).val().replace(/\n/g,"\n").replace(/\r/g,"\r"));
        array.push(dms);
    }
    return array;
}



//初始化字段编辑弹框
function initSqlStatementApiField(element) {
    var _this = $(element);
    var $table = _this.parents("table");
    var data =  $table.bootstrapTreeTable("getData");
    var index = _this.parents("tr").attr("dataid") -1;
    var row = data[index];
    BootstrapDialog.show({
        title : "编辑字段信息",
        cssClass : "drawer right",
        url: "/pages/dms/sqlStatementField.html",
        success : function(){
            $("#apiFieldData").data("apiFieldData",{index : index,field:row});
        },
        buttons: [
            {
                id: 'apiField-btn-ok',
                label: '确定',
                cssClass: 'btn-info',
                action: function(dialog) {
                    var index =  $("#apiFieldData").data("apiFieldData").index;
                    var row =  $("#apiField").serializable();
                    row.validator = $("#apiFieldValidator").serializable();
                    var dictionary = {};
                    if(row.validator.enums){
                        var enums = row.validator.enums.replace(/(\r\n)|\r|\n/g, '\n').split(/\n+/g);
                        for(var i = 0; i < enums.length ; i++){
                            if(enums[i]){
                                var dict = enums[i].split("=");
                                dictionary[dict[0]] = dict.length > 1 ?  dict[1] : null;
                            }
                        }
                        row.validator.enums = dictionary;
                    }
                    var data =  $table.bootstrapTreeTable("getData");
                    data[index]  = $.extend(data[index],row);
                    $table.bootstrapTreeTable("refresh");
                    dialog.close();
                },
            },
            {
                id: 'apiField-btn-secondary',
                label: '取消',
                cssClass: 'btn-light',
                action: function(dialog) {
                    if(typeof callback == 'function'){
                        callback(false);
                    }
                    dialog.close();
                },
            }
        ],
    });
}